package com.adfframeworks.labs.dao.impl;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import com.adfframeworks.labs.dao.RequestDAO;
import com.adfframeworks.labs.domain.Request;

@Repository
public class RequestDAOImpl extends JdbcDaoSupport implements RequestDAO {

	@Autowired
	RequestDAOImpl(DataSource dataSource) {
		setDataSource(dataSource);
	}
	
	@Override
	public void create(Integer from, Integer to, Integer community,
			Boolean ownerRequest) {
		String SQL = "INSERT INTO Request (Request_From, Request_To, Community_ID, Owner_Request) VALUES (?, ?, ?, ?)";
		getJdbcTemplate().update(SQL,
				new Object[] { from, to, community, ownerRequest });
		System.out.println("RequestDAOImpl.create(" + from + ", " + to + ", "
				+ community + ", " + ownerRequest + ")");
	}

	@Override
	public Request getRequest(Integer id) {
		String SQL = "SELECT * FROM Request WHERE Request_ID = ?";
		Request request = (Request) getJdbcTemplate().queryForObject(SQL,
				new Object[] { id }, new RequestMapper());
		return request;
	}

	@Override
	public List<Request> listAllRequests() {
		String SQL = "SELECT * FROM Request";
		List<Request> requests = getJdbcTemplate().query(SQL,
				new RequestMapper());
		return requests;
	}

	@Override
	public List<Request> listAllToRequests(Integer to) {
		String SQL = "SELECT * FROM Request WHERE Request_To = ?";
		List<Request> requests = getJdbcTemplate().query(SQL,
				new Object[] { to }, new RequestMapper());
		return requests;
	}

	@Override
	public List<Request> listOwnerToRequests(Integer to) {
		String SQL = "SELECT * FROM Request WHERE Request_To = ? AND Owner_Request = TRUE";
		List<Request> requests = getJdbcTemplate().query(SQL,
				new Object[] { to }, new RequestMapper());
		return requests;
	}

	@Override
	public List<Request> listNotOwnerToRequests(Integer to) {
		String SQL = "SELECT * FROM Request WHERE Request_To = ? AND Owner_Request = FALSE";
		List<Request> requests = getJdbcTemplate().query(SQL,
				new Object[] { to }, new RequestMapper());
		return requests;
	}

	@Override
	public void delete(Integer id) {
		String SQL = "DELETE FROM Request WHERE Request_ID = ?";
		getJdbcTemplate().update(SQL, new Object[] { id });
		System.out.println("RequestDAOImpl.delete(" + id + ")");
	}

	@Override
	public void update(Integer id, Integer from, Integer to, Integer community,
			Boolean ownerRequest) {
		String SQL = "UPDATE Request SET Name = ?, Owner = ?, KeyWord = ?, Visibility = ? WHERE Request_ID = ?";
		getJdbcTemplate().update(SQL,
				new Object[] { from, to, community, ownerRequest, id });
		System.out.println("RequestDAOImpl.update(" + id + ", " + from + ", "
				+ to + ", " + community + ", " + ownerRequest + ")");
	}

}
